#!/bin/bash
SYS_PATH=/etc/aops
OUT_PATH=/opt/aops/uwsgi
UWSGI_LOG_DIR=/var/log/aops/uwsgi
OPERATION=$1
AOPS_CONSTANT="aops"

function check_uwsgi_path() {
  if [ ! -d "$1" ];then
    mkdir -p $1
  fi
}

function check_file() {
  if [ ! -e "$1" ]; then
    touch "$1"
  fi
}

function get_config() {
  INIFILE=$1
  SECTION=$2
  ITEM=$3
  awk -F '=' '/\['"$SECTION"'\]/{a=1}a==1&&$1~/'"$ITEM"'/{print $2; exit}' "$INIFILE"
}

function create_config_file() {
  check_uwsgi_path $OUT_PATH
  check_uwsgi_path $UWSGI_LOG_DIR

  echo "[INFO] start to create uwsgi file"
  config_file=$1
  service_type=$2
  module_type=$3

  ip=$(get_config "${config_file}" "${service_type}" "ip")
  port=$(get_config "${config_file}" "${service_type}" "port")
  wsgi_file_name=$(get_config "${config_file}" "uwsgi" "wsgi-file")
  wsgi_file=$(find /usr/lib/python*/site-packages -maxdepth 1 -name ${module_type}"_"${service_type} | head -n 1)
  daemonize=$(get_config "${config_file}" "uwsgi" "daemonize")
  http_timeout=$(get_config "${config_file}" "uwsgi" "http-timeout")
  harakiri=$(get_config "${config_file}" "uwsgi" "harakiri")
  # module_name should be like this: adoctor-diag-scheduler which is joined with '-'
  array=(`echo ${service_type} | tr '_' ' '`)
  module_name=${module_type}
  for var in ${array[@]}
  do
    module_name=${module_name}"-"${var}
  done
  # module should be like this: adoctor_diag_scheduler which is joined with '_'
  module=${module_type}"_"${service_type}

  check_file $daemonize
  echo "[INFO] run $module_name under path: $wsgi_file"

  if [[ -z "$wsgi_file_name" ]] || [[ -z "$ip" ]] || [[ -z "$port" ]]; then
    echo "[ERROR] can not find  all config name in: ${config_file}, Please check the file."
    echo "[ERROR] The following config name is needed: ip, port and wsgi_file."
    exit 1
  fi
  if [ -z "$wsgi_file" ]; then
    echo "[ERROR] can not find the aops_${service_type} path under: /usr/lib/"
    exit 1
  fi

  echo "[uwsgi]
http=$ip:$port
chdir=$wsgi_file
module=${module}.manage
uwsgi-file=${wsgi_file_name}
pidfile=$OUT_PATH/${module_name}.pid
callable=app
http-timeout=${http_timeout}
harakiri=${harakiri}
daemonize=$daemonize" >"$OUT_PATH"/"${module_name}".ini
  chown root: $OUT_PATH/"${module_name}".ini
  chmod 750 $OUT_PATH/"${module_name}".ini
  echo "[INFO] create ${module_name} uwsgi file ok,path is $OUT_PATH/${module_name}.ini"
}

function check_num() {
  result=$(echo "$1" | grep '^[[:digit:]]*$')
  if [ -z "${result}" ]; then
    echo "[ERROR] $2 should be a number,please check this parameter "
    exit 1
  fi
}

function is_started() {
  aops_version=$(aops -v)
  if [[ -n ${aops_version} ]] && [[ ${aops_version} =~ "Version" ]]; then
    return 0
  else
    return 1
  fi
}

function start_service() {
  module_name=$1
  uwsgi -d --ini $OUT_PATH/"${module_name}".ini --enable-threads
  echo "[INFO] start uwsgi service: ${module_name} success"
  exit 0
}

function stop_service() {
  module_name=$1
  echo "[INFO] stop uwsgi service: ${module_name}"
  uwsgi --stop $OUT_PATH/"${module_name}".pid
  echo "[INFO] stop ${AOPS_CONSTANT} service success"
  exit 0
}

function start_or_stop_service() {
  if [ "${OPERATION}" = "start" ]; then
    start_service $1
  elif [ "${OPERATION}" = "stop" ]; then
    stop_service $1
  fi
}

function check_es_installed() {
  CONFIG_FILE=$1
  echo "[INFO] Elasticsearch check start"

  es_ip=$(get_config "$CONFIG_FILE" "elasticsearch" "ip")
  es_port=$(get_config "$CONFIG_FILE" "elasticsearch" "port")

  if [ -z "${es_ip}" ] || [ -z "${es_port}" ]; then
    echo "[ERROR] Can not find config name 'ip' or 'port' of elasticsearch in: $CONFIG_FILE,Please check the file"
    echo "If you have installed ES, Please set correct 'ip' value and 'port' of elasticsearch value and re-execute '${DATABASE_CONSTANT} start' "
    echo "If you have not installed ES, please execute the automatic installation script '/usr/bin/aops-basedatabase' under the root user "
    exit 1
  fi
  check_num "${es_port}" "es_port"
  # check whether to install Elasticsearch and started
  visit_es_response=$(curl -s -XGET http://"${es_ip}:${es_port}")
  if [ -z "${visit_es_response}" ]; then
    echo "========================================================================="
    echo "[ERROR] Elasticsearch connection FAILED,the following reason may cause failed:"
    echo "[INFO] 1. You have not installed Elasticsearch,If you need to install, please execute the automatic installation script '/usr/bin/aops-basedatabase' under the root user"
    echo "[INFO] 2. Elasticsearch configuration is incorrect,please update value of 'ip' and 'port' of elasticsearch in $CONFIG_FILE"
    echo "[INFO] 3. Elasticsearch service not started,please start elasticsearch service."
    exit 1
  fi
  echo "[INFO] Elasticsearch check ok"
}

function check_mysql_installed() {
  CONFIG_FILE=$1
  echo "[INFO] mysql check start"

  mysql_ip=$(get_config "$CONFIG_FILE" "mysql" "ip")
  port=$(get_config "$CONFIG_FILE" "mysql" "port")

  if [ -z "${mysql_ip}" ] || [ -z "${port}" ]; then
    echo "[ERROR] Can not find config name 'ip' or 'port' of mysql in: $CONFIG_FILE,Please check the file"
    echo "If you have installed mysql, Please set correct 'ip' value and 'port' value of mysql and re-execute '${DATABASE_CONSTANT} start' "
    echo "If you have not installed mysql, please execute the automatic installation script '/usr/bin/aops-basedatabase' under the root user "
    exit 1
  fi
  check_num "${port}" "port"

  aops_database=$(get_config "$CONFIG_FILE" "mysql" "database_name")
  create_aops_database=$(mysql -s -h "${mysql_ip}" -P ${port} -e "create database if not exists ${aops_database};" 2>&1)
  if [ -n "${create_aops_database}" ]; then
    echo "========================================================================="
    echo "[ERROR] mysql connection FAILED,the following reason may cause failed:"
    echo "[INFO] 1. You have not installed mysql,If you need to install, please execute the automatic installation script '/usr/bin/aops-basedatabase' under the root user"
    echo "[INFO] 2. mysql configuration is incorrect,please update value of 'ip' and 'port' of mysql in $CONFIG_FILE"
    echo "[INFO] 3. mysql service not started,please start mysql service."
    exit 1
  fi
  echo "[INFO] mysql check ok"
}